var express = require('express');
var axios = require('axios');
var router = express.Router();

var formidable = require("formidable");

/**
 * @api {get} /admin/launchExam 渲染页面
 * @apiName 渲染页面
 * @apiGroup createExam
 *
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.get('/',(req, res, next) => {
    if (req.session.login) {
        next()
    } else {
        res.send({ err: -999, msg: '请先登录' })
    }
}, function (req, res, next) {

    var config = {
        method: 'post',
        baseURL: 'http://localhost:9023',
        url: '/TestWord/getAll',
        params: {
            status: 1
        },
    }
    axios(config)
        .then(function (response) {
            console.log(response.data);
            if (response.data.code == 0) {
                console.log("获取试卷信息成功")
                res.render('admin/launchExam', {
                    list: response.data.data
                });
            } else {
                // console.log(response);
                res.send({ err: -1, msg: "获取试卷信息失败" })
                console.log("获取试卷信息失败")
            }
        })
        .catch(function (error) {
            // console.log(error);
            res.send({ err: -1, msg: "服务器错误，请刷新页面" })
            console.log("服务器错误")
        });

})

/**
 * @api {post} /admin/launchExam/build 创建考试
 * @apiName 创建考试
 * @apiGroup launchExam
 *
 * @apiParam {String} startTime 考试开始时间.
 * @apiParam {String} endTime 考试结束时间.
 * @apiParam {String} testWordId 使用试卷id.
 * @apiParam {String} remark 备注描述.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/build',(req, res, next) => {
    if (req.session.login) {
        next()
    } else {
        res.send({ err: -999, msg: '请先登录' })
    }
}, (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) throw err;
        console.log(fields);
        var config = {
            method: 'post',
            baseURL: 'http://localhost:9023',
            url: '/exam/build',
            params: fields,
        }
        axios(config)
            .then(function (response) {
                // console.log(response);
                if (response.data.code == 0) {
                    console.log("发布成功")
                    res.send({ err: 0, msg: "发布成功", data: response.data })
                } else {
                    // console.log(response);
                    res.send({ err: -1, msg: "发布失败" })
                    console.log("发布失败")
                }
            })
            .catch(function (error) {
                // console.log(error);
                res.send({ err: -1, msg: "服务器错误" })
                console.log("服务器错误")
            });
    });
})

module.exports = router;
